<template>
  <div class="reading-container">
    <!-- 左侧悬浮按钮 -->
    <div class="floating-buttons">
      <el-button @click="openTableOfContents" icon="el-icon-menu">目录</el-button>
      <el-button @click="showBookDetails" icon="el-icon-notebook-1">书详情</el-button>
      <el-button @click="addToBookshelf" icon="el-icon-folder-add">加书架</el-button>
      <el-button @click="vote" icon="el-icon-star-off">投票</el-button>
      <el-button @click="showSettings" icon="el-icon-setting">设置</el-button>
      <el-button @click="openPure" icon="el-icon-mobile-phone">纯净模式</el-button>
      <el-button @click="scrollTop" icon="el-icon-arrow-up">到顶部</el-button>
      <el-button @click="scrollButton" icon="el-icon-arrow-down">到底部</el-button>
    </div>

   

    <!-- 主阅读区域 -->
    <div class="main-content">
      <div class="content">
        <div class="book-top"></div>
        <div class="book-title" ref="contentTop">
          <h3>{{ chapter.title }}</h3>
        </div>
        <div v-for="(paragraph, index) in paragraphs" :key="index" class="book-content">
          <span v-html="paragraph"></span>
          <el-button v-if="userStore.isPureRead===false" size="small" class="inline-button" @click="showComments(index)">
            {{ commentMap.get(index + 1) }}
          </el-button>
        </div>
        <div></div>
        <!-- 底部的上一章和下一章导航按钮 -->
        <div class="navigation-buttons" ref="contentButton">
          <el-button @click="previousChapter" :disabled="!lastChapterId">上一章</el-button>
          <el-button @click="openTableOfContents">目录</el-button>
          <el-button @click="nextChapter" :disabled="!nextChapterId">下一章</el-button>
        </div>
      </div>
    </div>

    <!-- 评论区域 -->
    <div class="comment-section" v-if="selectedParagraph !== 0">
      <div class="comment-header">
        <h3>第 {{ selectedParagraph }} 段的评论</h3>
        <el-button @click="closeComments" type="danger" size="mini">关闭</el-button>
      </div>
      <chapterComment class="comment" :comments="commentData" :my_id="1"></chapterComment>
      <chapterCommentInput @submit="commitComment"></chapterCommentInput>
    </div>
  </div>

   <!-- 目录弹窗 -->
   <el-dialog class="dialog"
   v-model="isTableOfContentsVisible"
   width="30%"
   @close="closeTableOfContents"
 >
   <catalogue :book-id="chapter.bookId"></catalogue>
 </el-dialog>
</template>


<script setup lang="ts">
import { ref, onMounted, watch, onUnmounted, onBeforeUnmount } from 'vue';
import MarkdownIt from 'markdown-it';
import chapterComment from './components/chapterComment.vue';
import chapterCommentInput from './components/chapterCommentInput.vue';
import router from '@/router';
import { useRoute } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { log, time } from 'console';
import { useUserStore } from '@/stores/user';
import IconEpSunny from 'element-plus';
import IconEpMoon from 'element-plus';
import catalogue from '../components/catalogue.vue';
const userStore = useUserStore();
const userInfo = userStore.userInfo;
// 初始化评论、新评论和段落数据,与重载标签
const newComment = ref('');
const commentData = ref([]);
const selectedParagraph = ref(0);
const commentMap = ref<Map<number, number>>(new Map());


// Markdown渲染器配置
const md = new MarkdownIt({
  html: true,
  breaks: true,
  typographer: true
});

// 获取章节和书籍相关数据
const route = useRoute();
const chapterId = ref(route.params.id);
const chapter = ref({});
const chapterContent = ref('');
const paragraphs = ref<string[]>([]);
const lastChapterId = ref(null);
const nextChapterId = ref(null);

// 获取章节内容函数
const getChapter = async () => {
  try {
    const response = await axios.get(`/api/chapters/${chapterId.value}`);
    const { data } = response.data;

    chapter.value = data;
    console.log('书', chapter.value)
    chapterContent.value = md.render(data.content);

    lastChapterId.value = data.lastChapterId;
    nextChapterId.value = data.nextChapterId;

    paragraphs.value = chapterContent.value.split(/<\/?p>|<\/?h[1-6]>/).filter(text => text.trim());
  } catch (error) {
    console.error('Error fetching chapter:', error);
  }
};

// 获取段落评论数量函数
const getParagraphNumber = async () => {
  try {
    const response = await axios.get(`/api/chapter/comments/count/${chapterId.value}`);
    const data = response.data.data;
    const map = new Map<number, number>();

    for (const key in data) {
      if (Object.prototype.hasOwnProperty.call(data, key)) {
        map.set(Number(key), data[key]);
      }
    }
    commentMap.value = map;
  } catch (error) {
    console.error('Error fetching paragraph number:', error);
  }
};

// 初次挂载和监听路由变化
onMounted(() => {
  selectedParagraph.value = 0;
  getChapter();
  getParagraphNumber();
});
watch(() => route.params.id, () => {
  chapterId.value = route.params.id;
  getChapter();
  getParagraphNumber();
  scrollTop();
});

// 显示评论框
const showComments = (index: number) => {
  selectedParagraph.value = index + 1;

  axios.get(`/api/chapter/comments/${chapterId.value}/${selectedParagraph.value}`)
    .then((res) => {
      console.log(res);

      commentData.value = res.data.data;
      console.log("data:", commentData.value);
    });
};

// 提交评论
const commitComment = async (data: {
  text: string,
  emojiUrl: { emojiUrl: string, id: number }
}) => {
  console.log(data);
  const date = new Date();
  if (data.text.trim() !== '' && selectedParagraph.value !== null) {
    const commentPayload = {
      chapterId: chapterId.value,
      content: data.text,
      emojiUrl: data.emojiUrl?.emojiUrl,
      userEmojiId: data.emojiUrl?.id,
      ownerId: 1,
      fromId: userInfo.id,
      fromName: userInfo.username,
      fromAvatar: userInfo.profilePicture,
      date: new Date(date.getTime() - date.getTimezoneOffset() * 60000).toISOString().slice(0, 19),
      paragraph: selectedParagraph.value
    };
    try {
      const response = await axios.post('/api/chapter/comments/comment', commentPayload);
      if (response.status === 200) {
        ElMessage({ message: '评论创建成功', type: 'success' });
        getParagraphNumber();
        const t = selectedParagraph.value;

        setTimeout(() => {
          showComments(t - 1)
        }, 500);

      } else {
        throw new Error('Failed to submit comment');
      }
    } catch (error) {
      ElMessage({ message: '评论创建失败', type: 'error' });
    }
  }
};

// 关闭评论区域
const closeComments = () => {
  selectedParagraph.value = 0;
};

// 滚动到顶部和底部
const scrollTop = () => {
  const contentElement = document.querySelector('.book-top');
  if (contentElement) {
    contentElement.scrollIntoView({ behavior: 'smooth' });
  }
};

const scrollButton = () => {
  const contentElement = document.querySelector('.navigation-buttons');
  if (contentElement) {
    contentElement.scrollIntoView({ behavior: 'smooth' });
  }
};

// 上一章和下一章导航
const previousChapter = () => {
  selectedParagraph.value=0
  if (lastChapterId.value) {
    
    router.push(`/chapter_read/${lastChapterId.value}`);
  }
};

const nextChapter = () => {
  selectedParagraph.value=0
  if (nextChapterId.value) {
    router.push(`/chapter_read/${nextChapterId.value}`);
  }
};


const isTableOfContentsVisible = ref(false);

const toggleTableOfContents = () => {
 
};

const closeTableOfContents = () => {
  isTableOfContentsVisible.value = false;
};

// 当前章节的目录
const openTableOfContents = () => {
  isTableOfContentsVisible.value = !isTableOfContentsVisible.value;
  // chapterId
  axios.get('/api/chapters/summaries/' + chapterId.value)
    .then(response => {
      console.log(response.data);
      if (response.data.code === 200) {
        ElMessage({ message: "获取目录成功捏", type: 'success' });
      }
    })
    .catch(_ => {
      ElMessage({ message: "出现了一个未知的错误捏", type: 'error' });
    });

};


const showBookDetails = () => {
  router.push('/book_show/'+chapter.value.bookId);
};

const addToBookshelf = () => {
  // 加书架逻辑
};

const vote = () => {
  // 投票逻辑
};

const toggleNightMode = () => {
  // 夜间模式切换逻辑
  const body = document.body;
  body.classList.toggle('dark-mode');
};


//销毁时，设置白天

const showSettings = () => {
  // 显示设置面板
};

const openPure = () => {
  // 打开客户端
  userStore.isPureRead = !userStore.isPureRead;
};
</script>

<style scoped>


/* 阅读页面容器样式 */
.reading-container {
  background-color: var(--bPageBgColor);
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 左侧悬浮按钮样式 */
.floating-buttons {
  margin-top: 40px;
  position: fixed;
  left: 10px;
  top: 10%;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 主阅读内容样式 */
.main-content {
  display: flex;
  width: 60%;
  padding-left: 15%;
}

.book-top {
  height: 30px;
}

.book-title {
  margin-top: 30px;
  font-size: 24px;
  font-weight: bold;

}

/* 章节内容区样式 */
.content {
  flex-grow: 1;
  padding: 20px;
  background-color: var(--bReadContentBgColor);
  color: var(--bReadContentColor);
  overflow-y: auto;
  flex-direction: column;
}

.book-content {
  text-align: left;
  line-height: 1.6;
  margin-bottom: 20px;
}

.inline-button {
  display: inline-block;
  margin-left: 10px;
  vertical-align: middle;
}

/* 底部导航按钮样式 */
.navigation-buttons {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

/* 评论区样式 */
.comment-section {
  width: 20%;
  padding: 20px;
  border-left: 1px solid #ddd;
  background-color: var(--bReadContentBgColor);
  overflow-y: auto;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

@media  (max-width: 1000px) {
  
  .floating-buttons{
    display: none;
  }
}
</style>
<style>
.dialog{
  background: transparent;
  box-shadow: none; /* 去除阴影 */
}
</style>